import React, { Component, cloneElement } from 'react'
import FieldContext from '../../utils/context/FieldContext'

export default class Field extends Component {
  static contextType = FieldContext
  constructor(props) {
    super(props)
    this.state = {
      error: '',
      clearIsshow: false
    }
  }
  componentDidMount() {
    const { registerField } = this.context
    this.unregisterField = registerField(this)
  }

  componentWillUnmount() {
    if (this.unregisterField) {
      this.unregisterField()
    }
  }

  // store变化，执行这个刷新方法
  onStoreChange = () => {
    this.forceUpdate()
  }
  getControlled = () => {
    const { name, help, onsetAir } = this.props
    let obj = { name: name, isAir: false }
    const { getFieldValue, setFieldsValue } = this.context
    return {
      value: getFieldValue(name), //"omg", //比如说个仓库可以存储这个value，那这里直接get
      onChange: (event) => {
        const newValue = event.target.value
        setFieldsValue({ [name]: newValue })
        if (newValue.length > 0) {
          this.setState({ clearIsshow: true })
        } else {
          this.setState({ clearIsshow: false })
        }
        if (newValue === '') {
          obj.isAir = true
          onsetAir(obj)
        } else {
          obj.isAir = false
          onsetAir(obj)
        }
      },
      onsetair: () => {
        obj.isAir = true
        onsetAir(obj)
        setFieldsValue({ [name]: '' })
        this.setState({ clearIsshow: false })
      },
      name: name,
      help: help,
      clearIsshow: this.state.clearIsshow
    }
  }
  render() {
    const { children } = this.props
    const returnChildNode = React.cloneElement(children, this.getControlled())
    return returnChildNode
  }
}
